<!--
 * @author dumeng
 -->
<template>
  <div v-loading="pageLoading" class="app-container classify-page">
    <div class="classify-tab">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="item in dict.JNZQFL"
          :key="item.dictValue"
          :label="item.dictName"
          :name="item.dictValue"
        />
      </el-tabs>
    </div>
    <div class="classify-btn">
      <div class="btn-title">
        <span>分类管理</span>
      </div>
      <div class="btn-btns">
        <el-button v-if="!allListIsEdit" @click="handleAddClassify"
          >添加分类</el-button
        >
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :row-class-name="setRowClassName"
      size="mini"
      :indent="30"
      :cell-style="rowStyle"
      :header-cell-style="headerStyle"
      @row-click="handleRowClick"
    >
      <el-table-column label="分类名称">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-input
              v-model="scope.row.classifyName"
              class="edit-input"
              :class="[scope.row.parentId != -1 && 'children']"
              size="small"
            />
            <el-button
              v-if="scope.row.children && !allListIsEdit"
              class="addchild-btn"
              size="small"
              type="text"
              @click.stop="addchild(scope.row)"
              >添加子分类
            </el-button>
          </template>
          <template v-else>
            <span :class="[scope.row.parentId != -1 && 'children']">{{
              scope.row.classifyName
            }}</span>
            <el-button
              v-if="scope.row.children && !allListIsEdit"
              class="addchild-btn"
              size="small"
              type="text"
              @click.stop="addchild(scope.row)"
              >添加子分类
            </el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeTab === 'JNZQFL01' || activeTab === 'JNZQFL08'"
        label="分类图片"
        width="180"
      >
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-image
              :src="view + scope.row.imgId"
              @click.native="fileFlag = 1"
            >
              <div slot="error" style="cursor: pointer" class="image-slot">
                点击上传
              </div>
            </el-image>
            <image-no-cropper-upload
              v-if="fileFlag === 1"
              ref="imageUpload"
              accept="image/*"
              :limit="1"
              :multiple="false"
              @close="fileFlag = -1"
              @success="
                (id) => {
                  (scope.row.imgId = id), (fileFlag = -1);
                }
              "
            >
              <div slot="tip" class="upload-tip">
                <i class="el-icon-info" />
                建议上传尺寸：150px*150px
              </div>
            </image-no-cropper-upload>
          </template>
          <template v-else>
            <el-image
              :src="view + scope.row.imgId"
              :preview-src-list="[view + scope.row.imgId]"
            >
            <template v-slot:error>
              <img src="../images/error-icon.png" alt style="width: 100px;height: 100px; background: rgb(193, 187, 187);"/>
            </template>
          </el-image>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="ZT01"
            inactive-value="ZT02"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="
          activeTab === 'JNZQFL01' ||
          activeTab === 'JNZQFL08' ||
          activeTab === 'JNZQFL04'
        "
        label="职工端是否展示"
        width="200"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isAppVisit"
            active-value="1"
            inactive-value="0"
            @change="changeShow(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="移动" width="150">
        <template slot-scope="scope">
          <el-button
            :disabled="scope.row.isFirst"
            type="text"
            @click="move(scope.row, 'SY')"
            >上移</el-button
          >
          <el-button
            :disabled="scope.row.isLast"
            type="text"
            @click="move(scope.row, 'XY')"
            >下移</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleSave(scope.row)"
              >保存
            </el-button>
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleCancel(scope.row)"
              >取消
            </el-button>
          </template>
          <template v-else>
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleUpdate(scope.row)"
              >编辑
            </el-button>
          </template>
          <el-button
            v-if="activeTab === 'JNZQFL01' || activeTab === 'JNZQFL08'"
            type="text"
            style="color: #18a5fd; font-size: 14px"
            @click="handleAddress(scope.row.id)"
            >查看地址</el-button
          >
          <el-button
            type="text"
            style="color: #18a5fd; font-size: 14px"
            @click.stop="handleDel(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { getDictByCode, fetchList, del, insert, update, updateStatus, move } from '@/views/skill/category/api/index'
import permission from '@/directive/permission/index.js' // 权限判断指令
import ImageNoCropperUpload from '@/components/ImageNoCropperUpload'
export default {
  name: 'Category',
  directives: { permission },
  components: { ImageNoCropperUpload },
  filters: {
    formatStatus(val) {
      return val === 0 ? '启用' : val === 1 ? '禁用' : '禁用'
    },
    formatIshot(val) {
      return val === 0 ? '是' : val === 1 ? '否' : '否'
    }
  },
  data() {
    return {
      pageLoading: true,
      activeTab: '',
      listLoading: false,
      searchshow: true,
      expandAll: true,
      list: [],
      curEditRow: {},
      allListIsEdit: false, // 分类树是否存在编辑情况，如果存在隐藏所有的添加下级按钮
      sortable: null,
      dict: {
        JNZQFL: [], // 分类
        ZT: []
      },
      treeLevel: [],
      selectedId: '',
      selectNode: null,
      clientTop: 0,
      fileFlag: -1,
      view: '/API-DOCUMENT/document/file/download?id=',
      link1: '/StudyList?t=c&i=',
      link2: 'broadcast?c='
    }
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
    /* this.getList()*/
  },
  methods: {
    rowStyle({ row, columnIndex }) {
      console.log(columnIndex, 'ROW')
      if (columnIndex === 0) {
        return {
          textAlign: 'left'
        }
      } else {
        return {
          textAlign: 'center'
        }
      }
    },
    headerStyle({ row, columnIndex }) {
      if (columnIndex === 0) {
        return {
          textAlign: 'left'
        }
      } else {
        return {
          textAlign: 'center'
        }
      }
    },
    setRowClassName({ row }) {
      return row.id
    },
    handleRowClick(row) {
      return
      // 处理默认展开是页面滚动条问题
      if (row.id) {
        this.selectedId = row.id
        // .previousSibling
        this.selectNode = document.getElementsByClassName(row.id)[0]
        const scrollTop = document.getElementsByClassName('app-main')[0].scrollTop
        const offsetTop = document.getElementsByClassName(row.id)[0].offsetTop
        this.clientTop = offsetTop - scrollTop
      }
    },
    /**
       * 分类移动
       */
    move(row, dir) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        move({ id: row.id, msg: dir }).then(() => {
          this.$message({
            message: '处理成功',
            type: 'success',
            duration: 2000
          })
          loading.close()
          this.getList()
        }).catch(error => {
          loading.close()
          this.getList()
          reject(error)
        })
      })
    },
    /**
       * 切换启用禁用状态
       */
    changeStatus(row) {
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return new Promise((resolve, reject) => {
          updateStatus({ id: row.id, status: row.status }).then(() => {
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.getList()
          }).catch(error => {
            loading.close()
            this.getList()
            reject(error)
          })
        })
      }
    },
    /**
       * 切换是否在职工端展示
       */
    changeShow(row) {
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return new Promise((resolve, reject) => {
          update({ id: row.id, isAppVisit: row.isAppVisit }).then(() => {
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.getList()
          }).catch(error => {
            loading.close()
            this.getList()
            reject(error)
          })
        })
      }
    },
    /**
       * 获取字典
       */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
          if (code === 'JNZQFL') {
            this.activeTab = res.data.data[0] && res.data.data[0].list[0].dictValue
            this.getList()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
       * 选项卡切换
       */
    handleTabClick(tab, event) {
      this.selectedId = ''
      this.selectNode = null
      this.getList()
    },
    handleCancel(row) {
      if (row.id) {
        row['classifyName'] = this.curEditRow.classifyName
        row['status'] = this.curEditRow.status
        row['imgId'] = this.curEditRow.imgId
        this.findPathByLeafId(row.id, this.list).isEdit = false
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
      }
      this.allListIsEdit = false
    },
    handleUpdate(row) {
      if (this.allListIsEdit) {
        this.$message({
          message: '请先保存新添加分类',
          type: 'warning'
        })
        return
      } else {
        this.allListIsEdit = true
        this.curEditRow = Object.assign({}, row)
        this.findPathByLeafId(row.id, this.list).isEdit = true
      }
    },
    handleSave(row) {
      var obj = {
        id: row.id,
        classifyName: row.classifyName,
        status: row.status,
        parentId: row.parentId,
        classifyType: this.activeTab
      }
      if (this.activeTab === 'JNZQFL01') {
        obj.isAppVisit = row.isAppVisit
      }
      if (this.activeTab === 'JNZQFL01' || this.activeTab === 'JNZQFL08') {
        this.$set(obj, 'imgId', row.imgId,)
      }
      this.save(obj)
    },
    save(obj) {
      if (!obj.classifyName) {
        this.$message({
          message: '请填写分类名称',
          type: 'warning'
        })
        return
      }
      const pattern = new RegExp("^\\s|[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]|\\s$")
      if (pattern.test(obj.classifyName)) {
        this.$message({
          message: '请勿输入特殊字符或前后空格',
          type: 'warning'
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (obj.id) {
        return new Promise((resolve, reject) => {
          update(obj).then(() => {
            this.allListIsEdit = false
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      } else {
        return new Promise((resolve, reject) => {
          insert(obj).then(() => {
            this.allListIsEdit = false
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()

            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }
    },
    handleDel(row) {
      if (row.id) {
        this.$confirm('此操作将永久删除该课程分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.del(row.id)
        }).catch(() => {
        })
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
        this.allListIsEdit = false
        this.selectedId = row.id
        this.selectNode = document.getElementsByClassName(row.id)[0].previousSibling
      }
    },
    del(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        del({ id: id }).then(() => {
          loading.close()
          this.$message({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.selectedId = id
          this.selectNode = document.getElementsByClassName(id)[0].previousSibling
          this.getList()
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getList() {
      this.allListIsEdit = false
      this.listLoading = true
      return new Promise((resolve, reject) => {
        fetchList({ classifyType: this.activeTab }).then(response => {
          this.listLoading = false
          this.list = this.initData(response.data.data)
          this.pageLoading = false
          // 处理默认展开页面滚动条展开问题
          // this.$nextTick(() => {
          //   if (this.selectedId && this.selectNode) {
          //     const currentNode = document.getElementsByClassName('app-main')[0]
          //     const scollTop = this.selectNode.offsetTop
          //     if (scollTop) {
          //       currentNode.scrollTop = scollTop - this.clientTop
          //     }
          //     // this.selectNode.scrollIntoView()
          //   }
          // })
        }).catch(error => {
          this.listLoading = false
          this.pageLoading = false
          reject(error)
        })
      })
    },
    /**
       * 递归增加是否可以上移下移标识
       * @param data
       * @returns {*}
       */
    initData(data) {
      data.forEach((item, index) => {
        item['isFirst'] = false
        item['isLast'] = false
        item['isEdit'] = false
        if (index === 0) {
          item['isFirst'] = true
        }
        if (index === data.length - 1) {
          item['isLast'] = true
        }
        if (item.children && item.children.length > 0) {
          return this.initData(item.children)
        }
      })
      return data
    },
    addchild(row) {
      this.allListIsEdit = true
      row['_expanded'] = true
      let length = ''
      if (row.children) {
        length = row.children.length
      } else {

      }
      const obj = {
        id: '',
        classifyName: '',
        status: 'ZT01',
        isFirst: true,
        isLast: true,
        isEdit: true,
        parentId: row.id
      }
      if (this.activeTab === 'JNZQFL01') {
        obj.isAppVisit = row.isAppVisit
      }
      this.findPathByLeafId(row.id, this.list).children.unshift(obj)
      this.selectedId = row.id
      this.selectNode = document.getElementsByClassName(row.id)[0].previousSibling
    },
    /**
       * 根据id递归查找所在的对象
       * @param data
       * @returns {*}
       */
    findPathByLeafId(leafId, nodes, path) {
      if (path === undefined) {
        path = {}
      }
      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = path
        if (leafId == nodes[i].id) {
          tmpPath = nodes[i]
          return tmpPath
        }
        if (nodes[i].children) {
          var findResult = this.findPathByLeafId(leafId, nodes[i].children, tmpPath)
          if (findResult) {
            return findResult
          }
        }
      }
    },
    handleAddClassify() {
      this.allListIsEdit = true
      const list = this.list
      var length = list.length
      const obj = {
        id: '',
        parentId: '',
        classifyName: '',
        status: 'ZT01',
        isEdit: true,
        isFirst: true,
        isLast: true,
        index: length
      }
      if (this.activeTab === 'JNZQFL01') {
        obj.isAppVisit = '0'
      }
      list.unshift(obj)
      this.$set(this, 'list', list)
      this.selectedId = ''
      this.selectNode = null
    },
    handleFilter() {
      this.getList()
    },
    /**
       * 查看前端地址
       */
    handleAddress(id) {
      if (this.activeTab === 'JNZQFL01') {
        this.$confirm(`链接地址为：${this.link1}${id}<span style="color:red">注意：该链接只对已发布数据有效</span>`, '提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '复制链接',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const input = document.createElement('input')
          input.setAttribute('readonly', 'readonly')
          input.setAttribute('value', this.link1 + id)
          document.body.appendChild(input)
          input.select()
          if (document.execCommand('copy')) {
            document.execCommand('copy')
            this.$message({
              title: '成功',
              message: '复制成功！',
              type: 'success',
              duration: 1500
            })
          }
          document.body.removeChild(input)
        }).catch(() => {

        })
      } else if (this.activeTab === 'JNZQFL08') {
        this.$confirm(`链接地址为：${this.link2}${id}&${'t' + '=' + '中工电台'}&${'viewType' + '=' + 'warmtransceiver'}&${'imgShape' + '=' +'s'}<span style="color:red">注意：该链接只对已发布数据有效</span>`, '提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '复制链接',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const input = document.createElement('input')
          input.setAttribute('readonly', 'readonly')
          input.setAttribute('value', this.link2 + id + '&' + 't' + '=' + '中工电台' + '&' + 'viewType' + '=' + 'warmtransceiver' + '&' + 'imgShape' + '=' +'s')
          document.body.appendChild(input)
          input.select()
          if (document.execCommand('copy')) {
            document.execCommand('copy')
            this.$message({
              title: '成功',
              message: '复制成功！',
              type: 'success',
              duration: 1500
            })
          }
          document.body.removeChild(input)
        }).catch(() => {

        })
      }
    },
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
$dark_gray: #bfced6;
.classify-page {
  padding: 20px;
  .classify-tab {
    width: 100%;
    margin-bottom: 10px;
    background-color: #fff;
    padding: 0 10px;
    .el-tabs__header {
      margin: 0;
    }
  }
  .classify-btn {
    display: flex;
    height: 46px;
    line-height: 46px;
    .btn-title {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
  .el-table {
    background-color: transparent;
    /*.cell {
        display: flex;
        align-items: center;
      }*/
    thead {
      th {
        font-size: 14px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgb(193, 187, 187);
      }
    }
    th,
    tr {
      background-color: transparent;
    }
    tbody {
      background-color: #ffffff;
      font-weight: 500;
    }
  }
}
</style>
<style scoped lang="scss">
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
  vertical-align: middle;
}

.edit-input {
  padding-right: 80px;
  &.children {
    padding-left: 20px;
  }
}

.addchild-btn {
  position: absolute;
  right: 15px;
  top: 6px;
}
</style>

